package com.fivefu.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.exception.FfSqlAnalysisException;
import com.fivefu.core.param.FFParam;
import com.fivefu.core.pojo.FfSql;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/12
 */
@Component
public class PageSqlHandler implements  SqlHandler {

    @Override
    public void dealSql(JSONObject jsonObject, FfSql ffSql) throws FfSqlAnalysisException {
        if (jsonObject.containsKey(FFParam.KEY_PAGE) && jsonObject.containsKey(FFParam.KEY_PAGE_COUNT)) {
            int page = jsonObject.getInteger(FFParam.KEY_PAGE);
            page = page > 1 ? page : 1;
            int count = jsonObject.getInteger(FFParam.KEY_PAGE_COUNT);
            count = count > 0 ? count : 0;
            ffSql.setLimit(" limit " + (page - 1) * count + " ," + count);
        }

        if (jsonObject.containsKey(FFParam.KEY_IS_PAGE)) {
            Boolean pageFlag = jsonObject.getBoolean(FFParam.KEY_IS_PAGE);
            ffSql.setPageFlag(pageFlag);
        }
    }

    @Override
    public int order() {
        return 4;
    }

    private String errorMsg;

    @Override
    public String getErrMsg() {
        return this.errorMsg;
    }

    protected void setErrorMsg(String msg){
        this.errorMsg = msg;
    }
}
